package cn.ffcs.security.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import cn.ffcs.security.model.User;
import cn.ffcs.security.service.IUserService;
import cn.ffcs.security.web.UserContext;
import cn.ffcs.util.context.ApplicationContextUtil;

/**
 * 
 * 用户权限filter<br/> <table>
 * <tr>
 * <td>负责人/principal: </td>
 * <td colspan="2">liuzhh</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author liuzhh
 * @version $Id$
 */
public class SecurityFilter implements Filter
{
    /** 登录标识**/
    private static final String LOGIN_FLAG_="LOGIN";
    /** 用户标识**/
    private static final String LOGIN_USER_="LOGINUSER";
    /** 消息标识**/
    private static final String MESSAGE_="MSG";
    /** 用户服务**/
    private IUserService userService;
    /** 提示信息 **/
    private String message;
    
//    @Override
    public void destroy()
    {

    }

    @SuppressWarnings("unchecked")
//    @Override
    public void doFilter(ServletRequest sRequest, ServletResponse sResponse,
            FilterChain chain) throws IOException, ServletException
    {
        
        HttpServletRequest request = (HttpServletRequest) sRequest;
        HttpServletResponse response = (HttpServletResponse) sResponse;
        
        boolean bSucc=false;
        
        //操作标志
        String flag=request.getParameter("flag");
        
        //是否MIS登錄標志
        String misKey=request.getParameter("misKey");
        //System.out.println("flag:"+misKey);
        UserContext userContext=new UserContext();
        //判断是否OA单点登录
        if(misKey != null){
          //获取用户名和MIS登錄標志
            String userID_s =request.getParameter("userID_s");
            boolean isOper=false;
            String username=StringUtils.defaultIfEmpty(userID_s, "");
            User currUser=new User();
            currUser.setUserID(username.toUpperCase());
            currUser.setMisKey(misKey);
            int iResult=userService.checkUser(currUser);
            ApplicationContextUtil.setUserContext(request,userService.getUserContext());
            request.getSession().setAttribute(LOGIN_USER_, null);
            if (iResult==1){
                isOper=true;
                request.getSession().setAttribute(LOGIN_USER_, currUser);
                request.getSession().setAttribute("menus", userService.getUserContext().getMenus());
            }else if (iResult==-1){
                message="用户名不存在";
            }else if (iResult==-2){
                message="用户名和MIS登錄標志不匹配或MIS登錄標志不正确";
            }
            if (!isOper) {
            	request.setAttribute(MESSAGE_, message);
                response.sendRedirect(request.getContextPath()+"/login.jsp");
                return;
            }
        }
        
        //登录操作
        else if (StringUtils.equalsIgnoreCase(flag, LOGIN_FLAG_)){
            //获取用户名和密码
            String username=request.getParameter("username");
            String password=request.getParameter("password");
            username=StringUtils.defaultIfEmpty(username, "");
            User currUser=new User();
            currUser.setUserID(username.toUpperCase());
            currUser.setPassword(password);
            currUser.setMisKey(misKey);
            int iResult=userService.checkUser(currUser);
            ApplicationContextUtil.setUserContext(request,userService.getUserContext());
            boolean isOper=false;
            if (iResult==1){
                isOper=true;
                request.getSession().setAttribute(LOGIN_USER_, currUser);
                request.getSession().setAttribute("menus", userService.getUserContext().getMenus());
            }else if (iResult==-1){
                message="用户名不存在";
            }else if (iResult==-2){
                message="用户名和密码不匹配或密码不正确";
            }
            if (!isOper) {
            	request.setAttribute(MESSAGE_, message);
                response.sendRedirect(request.getContextPath()+"/login.jsp");
                return;
            }
        }
        else
        {
            // 判断用户是否已登录
            UserContext uc=ApplicationContextUtil.getUserContext(request);
            if (uc!=null){
                User currUser = ApplicationContextUtil.getUserContext(request).getCurrUser();
                if (currUser == null)
                {
                    message="您还未登录或会话已超时";
                    request.setAttribute(MESSAGE_, message);
                    response.sendRedirect(request.getContextPath()+"/toLogin.jsp");
                    return;
                }
            }else{
                message="您还未登录或会话已超时";
                request.setAttribute(MESSAGE_, message);
                response.sendRedirect(request.getContextPath()+"/toLogin.jsp");
                return;                
            }
        }
        
        chain.doFilter(request, response);
    }

//    @Override
    public void init(FilterConfig arg0) throws ServletException
    {
        // TODO Auto-generated method stub

    }

    /**
     * @return the userService
     */
    public IUserService getUserService()
    {
        return userService;
    }

    /**
     * @param userService the userService to set
     */
    public void setUserService(IUserService userService)
    {
        this.userService = userService;
    }

    /**
     * @return the message
     */
    public String getMessage()
    {
        return message;
    }

    /**
     * @param message the message to set
     */
    public void setMessage(String message)
    {
        this.message = message;
    }

}
